#!/usr/bin/env python
# -*- coding:utf-8 -*-

from app import db
from utils.response_code import RET, error_map_EN
from utils import commons
from models.repairInfoModel import RepairInfo
from models.repairImgInfoModel import RepairImgInfo
from utils.imgUtils import generate_path, generate_img_stream
from controller.repairImgInfoController import RepairImgInfoController
from controller.repairInfoController import RepairInfoController
from controller.workerInfoController import WorkerInfoController
from models.workerInfoModel import WorkerInfo
from datetime import datetime


class RepairInfoService(RepairInfoController):
    # 安排师傅方法
    @classmethod
    def arrangeWorker(cls, **kwargs):
        repairID = kwargs.get('repairID')
        workerID = kwargs.get('workerID')
        try:
            db.session.query(cls).filter(cls.repairID == repairID).update({'workID': int(workerID), 'status': 1})
            db.session.query(WorkerInfo).filter(WorkerInfo.workerID == workerID).update({'repairID': int(repairID),'status':1})
            # 安排师傅后更新repairInfo表中的updateTime字段
            update_info = {
                'repairID': repairID,
                'updateTime': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            RepairInfoController.update(**update_info)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库更新失败"}}
        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': error_map_EN[RET.OK]}

    # 完成维修方法
    @classmethod
    def finishRepair(cls, **kwargs):
        repairID = kwargs.get('repairID')
        workerID = kwargs.get('workerID')
        try:
            db.session.query(cls).filter(cls.repairID == repairID).update({'workID': 0, 'status': 2})
            db.session.query(WorkerInfo).filter(WorkerInfo.workerID == workerID).update({'repairID': 0, 'status':0})
            # 完成维修之后更新repairInfo表中的finishTime字段
            update_info = {
                'repairID': repairID,
                'finishTime': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            RepairInfoController.update(**update_info)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库更新失败"}}
        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': error_map_EN[RET.OK]}


    # 获取后台管理系统首页信息
    @classmethod
    def arrangementInfo(cls, **kwargs):
        try:
            repair_info = db.session.query(cls).all()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常,获取数据失败"}}
        repair_info_data_list = commons.query_to_dict(repair_info)
        result = []
        #获取维修信息
        for i in repair_info_data_list:
            repair_info_item = {
                'repairID': i.get('repairID'),
                'repairPlace': i.get('repairPlace'),
                'repairType': i.get('repairType'),
                'repairDetail': i.get('repairDetail'),
                'createTime': i.get('createTime'),
                'status': i.get('status'),
                'contactName': i.get('contactName'),
                'contactPhone': i.get('contactPhone'),
                'workID': i.get('workID'),
                'worker_name': '',
                'worker_phone': ''
            }
            workID = i.get('workID')
            repairID = i.get('repairID')
            # 查找维修师傅相关信息
            if workID:
                worker_info = WorkerInfoController.get(**{'repairID': repairID})
                if worker_info['data']:
                    worker_info = worker_info['data']
                    worker_name = worker_info[0]['workerName']  # 维修师傅姓名
                    worker_phone = worker_info[0]['workerPhone']  # 维修师傅电话
                    repair_info_item['worker_name'] = worker_name
                    repair_info_item['worker_phone'] = worker_phone
            #数据添加
            result.append(repair_info_item)

        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': result}

    # 实现后台管理系统的编号模糊查询
    @classmethod
    def fuzzy_search(cls, **kwargs):
        try:
            if kwargs.get('repairDetail'):
                search_info = cls.query.filter(
                    cls.repairDetail.like("%" + kwargs.get("repairDetail") + "%") if kwargs.get("repairDetail") is not None else ""
                ).all()

            results = commons.query_to_dict(search_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # 获取前台首页列表信息
    @classmethod
    def index(cls, **kwargs):
        try:
            repair_info = db.session.query(cls).all()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常,获取数据失败"}}
        repair_info_data_list = commons.query_to_dict(repair_info)
        result = []
        for i in repair_info_data_list:
            repair_info_item = {
                'repairID': i.get('repairID'),
                'repairPlace': i.get('repairPlace'),
                'repairType': i.get('repairType'),
                'repairDetail': i.get('repairDetail'),
                'createTime': i.get('createTime'),
                'status': i.get('status')
            }
            result.append(repair_info_item)
        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': result}

    # 获取我的报修单列表信息
    @classmethod
    def myIndex(cls, **kwargs):
        userID = kwargs.get('userID')
        try:
            repair_info = db.session.query(cls).filter(cls.userID == userID).all()

        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常,获取数据失败"}}
        repair_info_data_list = commons.query_to_dict(repair_info)
        result = []
        for i in repair_info_data_list:
            repair_info_item = {
                'repairID': i.get('repairID'),
                'repairPlace': i.get('repairPlace'),
                'repairType': i.get('repairType'),
                'repairDetail': i.get('repairDetail'),
                'createTime': i.get('createTime'),
                'status': i.get('status')
            }
            result.append(repair_info_item)
        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': result}

    # 提交报修单
    @classmethod
    def submit_repair_info(cls, **kwargs):
        # 生成维修订单逻辑主键repairID  生成维修图片逻辑主键ID
        try:
            from utils.generate_id import GenerateID
            repairID = GenerateID.create_random_id()
            imgID = GenerateID.create_random_id()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': '数据库生成ID错误'}}

        # 添加维修记录
        try:
            # status默认是0刚开始修的时候 isDelete默认也是0
            repair_info = RepairInfo(
                repairID=int(repairID),
                repairPlace=kwargs.get('repairPlace'),
                repairType=kwargs.get('repairType'),
                repairDetail=kwargs.get('repairDetail'),
                contactName=kwargs.get('contactName'),
                contactPhone=kwargs.get('contactPhone'),
                userID=kwargs.get('userID')
            )
            # 添加维修图片
            # 拿到一个FileStorage对象
            img_list = kwargs.get('repairInfoImg')
            # 添加到数据库
            # generate_path是生成图片路径并保存到目录下
            for img in img_list:
                file_path = generate_path(img)
                info = {
                    'imgSrc': file_path,
                    'repairInfoID': int(repairID)
                }
                RepairImgInfoController.add(**info)
            db.session.add(repair_info)
            db.session.commit()
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': error_map_EN[RET.OK]}
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': '数据库链接异常，无法添加记录'}}
        finally:
            db.session.close()

    # 获取报修单详情
    @classmethod
    def get_repair_detail(cls, **kwargs):
        result = RepairInfoController.get(**kwargs)
        if result['code'] != RET.OK:
            # 失败的结果集对象
            return {'code': result['code'], 'message': result['message'], 'data': {'error': '没有查询到相关维修记录'}}
        else:
            # 成功查询到的结果
            # 维修记录相关信息
            repair_info = result['data'][0]
            repairType = repair_info.get("repairType")  # 报修类型
            repairPlace = repair_info.get("repairPlace")  # 报修地点
            repairDetail = repair_info.get("repairDetail")  # 报修描述
            contactName = repair_info.get("contactName")  # 联系人姓名
            contactPhone = repair_info.get("contactPhone")  # 联系人电话
            status = repair_info.get("status")  # 维修状态
            workID = repair_info.get("workID")  # 维修师傅ID
            createTime = repair_info.get("createTime")  # 获取提交维修时间
            updateTime = repair_info.get('updateTime')  # 获取此时收到安排维修师傅的时间
            finishTime = repair_info.get('finishTime')  # 获取订单完成时间
            worker_name = ''
            worker_phone = ''

            # 查找维修师傅相关信息
            if workID:
                worker_info = WorkerInfoController.get(**{'repairID': kwargs.get('repairID')})
                if worker_info['data']:
                    worker_info = worker_info['data']
                    worker_name = worker_info[0]['workerName']  # 维修师傅姓名
                    worker_phone = worker_info[0]['workerPhone']  # 维修师傅电话

            # 查找维修记录repairID对应的图片
            repairID = kwargs.get('repairID')
            repair_img_info = db.session.query(RepairImgInfo).filter(RepairImgInfo.repairInfoID == repairID).all()
            repair_img_info_list = []
            for repair_img in repair_img_info:
                # 拿到图片表的每个记录
                repair_img = commons.query_to_dict(repair_img)
                img_src = repair_img['imgSrc']
                img_stream = generate_img_stream(img_src)
                # 加入base64流列表
                repair_img_info_list.append(img_stream)



            # 把所有获取到的数据封装成字典返回
            resp_detail = {
                'repairType': repairType,
                'repairPlace': repairPlace,
                'repairDetail': repairDetail,
                'status': status,
                'contactName': contactName,
                'contactPhone': contactPhone,
                'workerName': worker_name,
                'workerPhone': worker_phone,
                'repairImgInfo': repair_img_info_list,
                'createTime': createTime,
                'updateTime': updateTime,
                'finishTime': finishTime,
            }

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': resp_detail}
